<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Session;
use think\Db;
use app\common\model\StoreConfig;
use app\admin\model\exchange\Ordergas;
use app\admin\model\exchange\Ordergoods;
use app\admin\model\exchange\Orderrecharge;
use app\admin\model\exchange\OrderGasInfo;
use app\admin\model\exchange\OrderGoodsInfo;
use app\admin\model\exchange\Order;
/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $store_no = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $user_info = Session::get('admin');//获取当前登录用户信息
        $this->store_no = $user_info['store_no'];
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where('store_no',$this->store_no)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $ids_arr = explode(',',$ids);
        foreach ($ids_arr as $item){
            $row = $this->model->get($item);
            $this->modelValidate = true;
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            Auth::instance()->delete($row['id']);
        }

        $this->success();
    }
    
              /**
     * 充值
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function show($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if (false === $this->request->isPost()) {        	
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $user_info = Session::get('admin');//获取当前登录用户信息
        $params['agent_id'] = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        
        $gift_amount = 0;
    	$storeset = StoreConfig::where('name','rechange')->where('store_no',$store_no)->find();
    
    	$recharge = json_decode($storeset['value'],true);
    	if(!empty($recharge))
    	{
    		foreach ($recharge as $k => $v) {
    			if($params['money'] >=$k&&$gift_amount<$v)$gift_amount = $v;
    		}
    	}
    	$allmoney = round($params['money']+$gift_amount,2);
        $this->model::where('id', $row->id)->setInc('money', $allmoney);

    	$osn = date('YmdHis') . rand(10000000,99999999);
//  	$oil = Gasset::where('id',$gas_id)->find();
//  		if(!$oil)$this->error('油号不存在');
//  		$paramgas['agent_id']=1;
	        $paramgas['store_no']=$store_no;
	        $paramgas['user_id']=$row->id;
	        $paramgas['order_no']=$osn;
	        $paramgas['total_price']=$allmoney;
	        $paramgas['total_pay_price']=$allmoney;
	        $paramgas['discount_price']=0;
	        $paramgas['gift_amount']=$gift_amount;
	        $paramgas['is_pay']=2;
	        $paramgas['pay_type']=5;
	        $paramgas['pay_way']=4;
	        $paramgas['pay_time']=time();
	        $paramgas['source_type']=2;
    		$resultgas = Orderrecharge::create($paramgas);
    		if($resultgas)
    		{

	    		//录入总订单
		        $paramse['store_no']=$store_no;
		        $paramse['user_id']=$row->id;
		        $paramse['order_no']=$osn;
		        $paramse['total_price']=$allmoney;
		        $paramse['total_pay_price']=$allmoney;
		        $paramse['discount_price']=0;
		        $paramse['gift_amount']=$gift_amount;
		        $paramse['is_pay']=2;
		        $paramse['pay_type']=5;
		        $paramse['type']=1;
		        $paramse['source_type']=2;
		        $paramse['pay_time']=time();
		        $paramse['pay_way']=4;
		    
		    	$result = Order::create($paramse);

    		}
        
        $this->success();
    }

}
